<template>
  <!-- <div>menu-tree-select</div> -->
  <!-- show-checkbox -->
  <client-only>
    <el-tree-select
      placeholder="选择菜单"
      v-bind="$attrs"
      v-model="value"
      :data="menuTree"
      node-key="key"
      :props="{
        value: 'key',
        label: 'title',
        disabled: props.propsDisabled,
      }"
    ></el-tree-select>
    <!-- <el-tree
      class="w-full"
      :data="menuTree"
      show-checkbox
      node-key="key"
      :props="{
        value: 'key',
        label: 'title',
        disabled: props.propsDisabled,
      }"
      auto-expand-parent
      default-expand-all
      :expand-on-click-node="false"
      :check-strictly="true"
      :default-checked-keys="checkedKeys"
      @check="onCheck"
    ></el-tree> -->
  </client-only>
</template>

<script setup lang="ts">
import { reverse } from 'lodash-es';
import { MenuType, Menu } from '~~/types/menu.d';
// import { MenuMapItem, MenuMap } from '~~/utils/useMenus';

const props = defineProps({
  modelValue: { type: String, default: null },
  propsDisabled: { type: Function, default: (item) => false },
});
const emit = defineEmits(['update:modelValue']);

const value = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  },
});

const menus = useFetchApi('/system/menu', {
  key: 'get-system-menu',
  query: {
    // status: Status.enable,
  },
  default: () => <Menu[]>[],
});
const menuMap = computed(() => {
  const list = menus.data.value || [];

  const map = list.reduce((map, value) => {
    value.children = [];
    // value.label = value.title;
    // value.value = value.key;
    // value.disabled = false;
    map.set(value.key, value);
    return map;
  }, new Map());

  list.forEach((value) => {
    if (value.parent && map.has(value.parent)) {
      const parent = map.get(value.parent);
      const item = map.get(value.key);
      parent.children.push(item);
    }
  });
  return map;
});

const menuTree = computed(
  () =>
    menus.data.value
      ?.filter((value) => !value.parent)
      .map((value) => {
        const data = menuMap.value.get(value.key);
        return data;
      }) || [],
);

// const checkedKeys = ref([]);
// function onCheck(data, { checkedKeys }) {
//   if (checkedKeys.includes(data.key)) {
//     // checkedKeys.push(data.key);
//     checkedKeys.value = [data.key];
//   } else {
//     // checkedKeys.push(data.key);
//     checkedKeys.value = [];
//   }
// }
</script>

<style scoped lang="scss"></style>
